package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.MyMessage;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mac on 15-6-24.
 */
public class ManageModelActivity extends Activity implements View.OnClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener, View.OnTouchListener {

    private GridView mGridView;
    private LinearLayout mBack;
    private RelativeLayout mDismissLayout;
    private TextView mTvOk;

    private int mPosition;
    private List<EventListData> mResultData = new ArrayList<EventListData>();
    private MyGridViewAdapter mAdapter;
    private PreferenceUtil mPreferenceUtil;
    private CloudDBOperation mCloudDBOperation;

    private final static int GET_MODEL = 1890;
    private final static int GET_MODEL_BACK = 1891;
    private final static int DELETE_MODEL = 1892;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_MODEL:
                    if (msg.arg1 == 0) {

                        mResultData = (List<EventListData>) msg.obj;
                        mAdapter = new MyGridViewAdapter();
                        mGridView.setAdapter(mAdapter);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageModelActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageModelActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case DELETE_MODEL:
                    if (msg.arg1 == 0) {
                        mCloudDBOperation.deleteEventModelByEventId(mResultData.get(mPosition).getEventId());
                        mResultData.remove(mPosition);
                        mAdapter = new MyGridViewAdapter();
                        mGridView.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageModelActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageModelActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_model_layout);
        initView();
        initProperty();

    }

    public void initProperty() {

        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mCloudDBOperation = new CloudDBOperation(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new AsyncTask<String, Void, List<EventListData>>() {

            @Override
            protected List<EventListData> doInBackground(String... strings) {
                //EventListData headData = null;
                if (mResultData != null) {
                    mResultData.clear();
                }
                /*List<EventListData> modelData = mCloudDBOperation.findAllEventsByWhere("1");
                mResultData.addAll(modelData);*/
                mResultData = mCloudDBOperation.findAllEventsModel();
                return mResultData;
            }

            @Override
            protected void onPostExecute(List<EventListData> EventListDatas) {
                super.onPostExecute(EventListDatas);
                mAdapter = new MyGridViewAdapter();
                mGridView.setAdapter(mAdapter);
            }
        }.execute();

    }

    public void getCustomModel() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        MyMessage.GetCustomModelMessage message = new MyMessage.GetCustomModelMessage(mHandler.obtainMessage(GET_MODEL), this);
        message.mApi = AsynHttpClient.API_EVENT_GET_TEMPLATES;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);


    }

    public void initView() {
        mDismissLayout = (RelativeLayout) findViewById(R.id.model_ll_dismiss);
        mGridView = (GridView) findViewById(R.id.model_gv);
        mBack = (LinearLayout) findViewById(R.id.model_ll_back);
        mTvOk = (TextView) findViewById(R.id.model_tv_ok);

        mGridView.setOnItemClickListener(this);
        mGridView.setOnItemLongClickListener(this);

        mBack.setOnClickListener(this);
        mTvOk.setOnClickListener(this);
        mDismissLayout.setOnTouchListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.model_ll_back:
                finish();
                break;
            case R.id.model_tv_ok:
                if (mResultData != null) {
                    if ( mResultData.size() > 3 ) {
                        Toast.makeText(this, "自定义模板最多4个，请长按删除", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(this, CustomEventActivity.class);
                        //startActivityForResult(intent, GET_MODEL_BACK);
                        startActivity(intent);
                    }
                }
                break;
        }

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        mAdapter.setCanDelete(true);
        mAdapter.notifyDataSetChanged();
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        EventListData customModelData = mResultData.get(i);
        Intent intent = new Intent(ManageModelActivity.this, CustomEventActivity.class);
        Bundle bundle1 = new Bundle();
        bundle1.putString("type", "5");
        bundle1.putString("event_tmp_id", customModelData.getEventId());
        bundle1.putString("event_type", customModelData.getEventName());
        if (StringUtil.isEmpty(customModelData.getReceiver())) {
            bundle1.putString("event_receiver", "");
        } else {
            bundle1.putString("event_receiver", customModelData.getReceiver());
        }
        bundle1.putString("event_theme", customModelData.getEventTitle());
        bundle1.putString("event_hint1", customModelData.getInitTitle1());
        bundle1.putString("event_hint2", customModelData.getInitTitle2());
        bundle1.putString("event_hint3", customModelData.getInitTitle3());
        intent.putExtra("event_msg", bundle1);
        //startActivityForResult(intent, GET_MODEL_BACK);
        startActivity(intent);
    }

    // 取消 X 号
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        mAdapter.setCanDelete(false);
        mAdapter.notifyDataSetChanged();
        return false;
    }

    public void deleteModel(String eventId) {

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TMP_EVENT_ID, eventId));
        MyMessage.DeleteCustomModelMessage message = new MyMessage.DeleteCustomModelMessage(mHandler.obtainMessage(DELETE_MODEL));
        message.mApi = AsynHttpClient.API_EVENT_DELETE_TEMPLATES;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_MODEL_BACK:
                if (resultCode == RESULT_OK) {
                    // getCustomModel();
                }
                break;
        }
    }

    class MyGridViewAdapter extends BaseAdapter {

        private boolean isCanDelete;

        @Override
        public int getCount() {
            return mResultData.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        public void setCanDelete(boolean flag) {
            isCanDelete = flag;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(ManageModelActivity.this).inflate(R.layout.gridview_layout, null);
                holder.mIvDelete = (ImageView) view.findViewById(R.id.custom_iv_delete);
                holder.mEventName = (TextView) view.findViewById(R.id.custom_tv_name);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.mEventName.setText(mResultData.get(i).getEventName());
            if (isCanDelete) {
                holder.mIvDelete.setVisibility(View.VISIBLE);
            } else {
                holder.mIvDelete.setVisibility(View.GONE);
            }
            holder.mIvDelete.setOnClickListener(new DeleteOnClick(i));
            return view;
        }

        class DeleteOnClick implements View.OnClickListener {

            private int position;

            public DeleteOnClick(int position) {
                this.position = position;
            }

            @Override
            public void onClick(View view) {
                ManageModelActivity.this.mPosition = position;
                ManageModelActivity.this.deleteModel(mResultData.get(position).getEventId());
            }
        }
    }

    class ViewHolder {
        ImageView mIvDelete;
        TextView mEventName;

    }

}
